package com.ds.lens.data.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * Description:
 *
 * @author WeiShaoying
 * @date 2020-02-12
 */
@Repository
@Slf4j
public class RedisClient {

    @Autowired
    private StringRedisTemplate redisTemplate;


    public Boolean del(String key) {
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        return redisTemplate.delete(key);
    }

    public boolean set(String key, String val) {
        try {
            redisTemplate.opsForValue().set(key, val);
            return true;
        } catch (Exception e) {
            log.error("Redis set error.", e);
            return false;
        }
    }

    public boolean setWithExpiration(String key, String val, long time, TimeUnit timeUnit) {
        if (time <= 0) {
            return false;
        }
        try {
            redisTemplate.opsForValue().set(key, val, time, timeUnit);
            return true;
        } catch (Exception e) {
            log.error("Redis set error.", e);
            return false;
        }
    }

    public String getString(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 获取并重新设置过期时间
     *
     * @param key
     * @param timeout
     * @param timeUnit
     * @return
     */
    public String getAndTouch(String key, long timeout, TimeUnit timeUnit) {
        if (key == null) {
            return null;
        }
        String val = redisTemplate.opsForValue().get(key);
        if (val != null) {
            expire(key, timeout, timeUnit);
        }
        return val;
    }

    /**
     * 功能描述：设置某个key过期时间
     * 时间单位为秒
     *
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key, long time) {
        return expire(key, time, TimeUnit.SECONDS);
    }

    /**
     * 功能描述：设置某个key过期时间
     *
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key, long time, TimeUnit timeUnit) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, timeUnit);
            }
            return true;
        } catch (Exception e) {
            log.error("Redis expire error.", e);
            return false;
        }
    }

}
